package com.namo.cchapi.service.impl;

import cn.hutool.captcha.LineCaptcha;
import com.namo.cchapi.entity.PicCaptchaEntity;
import com.namo.cchapi.service.PicCaptchaService;
import com.namo.cchapi.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.UUID;

/**
 * @author WangXin
 * @date 2021/4/12 10:46
 */
@Service
public class PicCaptchaServiceImpl implements PicCaptchaService {
    @Autowired
    RedisService redisService;
    @Autowired
    LineCaptcha lineCaptcha;

    @Value("${captcha.time}")
    Long time;


    @Override
    public PicCaptchaEntity createPicCaptcha() throws IOException {
        lineCaptcha.createCode();
        String imageBase64 = lineCaptcha.getImageBase64();
        PicCaptchaEntity picCaptchaEntity = new PicCaptchaEntity();
        picCaptchaEntity.setCode(lineCaptcha.getCode());
        picCaptchaEntity.setImage("data:image/png;base64,"+imageBase64);
        picCaptchaEntity.setTime(time);
        picCaptchaEntity.setId(UUID.randomUUID().toString());
        redisService.set("cch:captchas:"+ picCaptchaEntity.getId(), picCaptchaEntity,time);
        return picCaptchaEntity;
    }

    @Override
    public boolean checkPicCaptcha(String id,String inputCode) throws Exception {
        //获取验证码
        Object captchaObject = redisService.get("cch:captchas:" + id);
        //判断是否为空
        if (captchaObject == null){
            throw new Exception("验证码过期");
        }
        PicCaptchaEntity picCaptchaEntity = (PicCaptchaEntity) captchaObject;
        String code = picCaptchaEntity.getCode();
        //比较验证码
        if (code .equals(inputCode)){
            //删除已经验证通过的验证码
            redisService.del("cch:captchas:" + id);
            return true;
        }else {
            throw new Exception("验证码不正确");
        }
    }
}
